<?php

namespace app\api\controller;


use think\App;
use think\exception\HttpResponseException;
use think\Request;
use app\BaseController;


class Api extends BaseController
{

    /**
     * 请求GET参数
     * @var array
     */
    public $get = [];


    /**
     * 请求POST参数
     * @var array
     */
    public $post = [];



    /**
     * 请求参数对象
     * @var Request
     */
    public $request;


    /**
     * @var
     */
    public $app;

    /**
     * @var
     */
    public $user;

    /**
     * 控制器初始化
     */
    protected function initialize()
    {
        $this->app = app();
        $this->request =$this->app->request;
        $this->get =  $this->request->get();
        $this->user =  $this->request->user;
        $this->post =  $this->request->post();

    }

    /**
     * 返回失败的内容
     * @param mixed $info 消息内容
     * @param mixed $data 返回数据
     * @param mixed $code 返回代码
     */
    public function error($info, $data = '{-null-}', $code = 0): void
    {
        $this->success($info, $data, $code);
    }

    /**
     * 返回成功的内容
     * @param mixed $info 消息内容
     * @param mixed $data 返回数据
     * @param mixed $code 返回代码
     */
    public function success($info, $data = '{-null-}', $code = 1): void
    {
        if ($data === '{-null-}') $data = new \stdClass();
        $result = ['code' => $code, 'info' => is_string($info) ? lang($info) : $info, 'data' => $data];
        throw new HttpResponseException(json($result));

    }



    /**
     * 重写验证规则
     * @param array $data
     * @param array|string $validate
     * @param array $message
     * @param bool $batch
     * @return bool
     */
    public function validate(array $data, $validate, array $message = [], bool $batch = false): bool
    {
        try {
            parent::validate($data, $validate, $message, $batch);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        return true;
    }

    protected function checkPostRequest()
    {
        if (!$this->request->isPost()) {
            $this->error("当前请求不合法！");
        }
    }

}